package edu.spec.wechat.quartz;

import edu.spec.wechat.model.AccessToken;
import edu.spec.wechat.model.ErrorEntity;
import edu.spec.wechat.model.WechatFianlValue;
import edu.spec.wechat.web.WechatContext;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.madgecko.basic.util.JsonUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * Created by Administrator on 2016/10/16 0016.
 */

@Component
public class RefreshAccessTokenTask {

    public void refreshToken() {
        CloseableHttpClient client = null;
        HttpGet get = null;
        CloseableHttpResponse resp = null;
        try {
            client = HttpClients.createDefault();
            String url = WechatFianlValue.ACCESS_TOKEN_URL;
            WechatContext wc = WechatContext.getInstance();
            url = url.replace("APPID", wc.getAppID()).replace("APPSECRET", wc.getAppsecrect());
            get = new HttpGet(url);
            resp = client.execute(get);
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                HttpEntity entity = resp.getEntity();
                String content = EntityUtils.toString(entity);
                System.out.println(content);
                try {
                    AccessToken at = (AccessToken) JsonUtil.getInstance().json2obj(content, AccessToken.class);
                    WechatContext.getInstance().setAccessToken(at.getAccess_token());
                    System.out.println("AccessToken:" + at.getAccess_token());
                } catch (Exception e) {
                    ErrorEntity er = (ErrorEntity) JsonUtil.getInstance().json2obj(content, ErrorEntity.class);
                    System.out.println("获取access_token异常:" + er.getErrcode() + ", " + er.getErrmsg());
                    refreshToken();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (resp != null) {
                try {
                    resp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client!=null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
